//
//  EFSelectCollectionMenu.m
//  MyCollectionView
//
//  Created by xinqing on 15/9/14.
//  Copyright (c) 2015年 pansoft. All rights reserved.
//

#import "EFSelectCollectionMenu.h"
#import "ViewControllerManager.h"
#import "Constant.h"
#import "MBProgressHUD.h"
#import "EnvironmentVariable.h"
#import "sys/utsname.h"
#import "Masonry.h"
#import "JFLanguageManager.h"

#define LAYOUT_HEIGHT 90
#define LAYOUT_WIDTH 50
#define SCROLL_DIRECTION UICollectionViewScrollDirectionVertical
#define PAGE_CONTROL_HEIGHT 10
#define SELECTED_KEY @"checked"



@implementation EFSelectCollectionMenu{
    UICollectionView *_collectionView;
    UICollectionViewFlowLayout *_flowLayout;
    
    NSDictionary *_checkDict;//plist
    
    BOOL                            _isIpX;
}

-(instancetype)initWithData:(NSMutableArray *)stubObjects
{
    CGRect frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , [[UIScreen mainScreen] bounds].size.height);
    self = [self initWithFrame:frame datas:stubObjects];
    return self;
}

//-(void)deviceIdentify {
//    struct utsname systemInfo;
//    uname(&systemInfo);
//    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
//    _isIpX = NO;
//    if([deviceString isEqualToString:@"iPhone10,3"] || [deviceString isEqualToString:@"iPhone10,6"] || [deviceString isEqualToString:@"x86_64"]) {
//        _isIpX = YES;
//    }
//}

-(instancetype)initWithFrame:(CGRect)frame datas:(NSMutableArray *) stubObjects{
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor whiteColor];
    if (self) {
        
        //1 全选复选框
        _allSelectCheckBox = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(5, 0, 80, 30) style:kSSCheckBoxViewStyleMono checked:NO];
        [_allSelectCheckBox setText:[JFLanguageManager stringWithKey:@"ESShopSelectall" table:Table_EShopComps comment:@"全选"]];
        
        [self addSubview:_allSelectCheckBox];
        [_allSelectCheckBox setStateChangedBlock:^(SSCheckBoxView *v) {
            if (v.checked) {
                [self selectAll];
            }else{
                [self deselectAll];
            }
        }];
        
        //2 保存按钮
        //创建圆角button
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //指定button的位置和大小
        CGRect cbFrame= _allSelectCheckBox.frame;
        CGFloat saveButtonWidth = 300;
        CGFloat saveButtonHeight = 44;
        [self addSubview:_saveButton];
        [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self).with.offset(0);
            make.height.equalTo(@50);
        }];
        
        //        _saveButton.frame = CGRectMake((frame.size.width - saveButtonWidth)/2, frame.size.height - saveButtonHeight, saveButtonWidth, saveButtonHeight);
        //给button设置标签，用来辨别点击的是哪个button，常用在委托方法中。
        _saveButton.tag = 0;
        //定义按钮标题
        [_saveButton setTitle:JFLanguageManager.save forState:UIControlStateNormal];
        [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_saveButton setBackgroundColor:EF_RED_COLOR];
        //定义按钮标题字体格式
        [_saveButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
        //        [saveButton.titleLabel setTextColor:[UIColor blackColor]];
        //给button添加委托方法，即点击触发的事件。
        [_saveButton addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
        
        
        //3 colectionView
        self.columnCount = 4;
        
        self.items = stubObjects;
        //处理 “全选” 复选框
        [self manageAllSelectedCheckBox];
        
        [self setBackgroundColor:[UIColor clearColor]];
        
        _cellImageWidth = 50;
        _cellImageHeight = 50;
        _cellTitleHeight = 20;
        _cellTitleFontSize = 16;
        _cellTitleTextColor = [UIColor blackColor];
        _cellBackgroudColor = [UIColor clearColor];
        
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat collectionViewY = _allSelectCheckBox.frame.size.height + 5;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, collectionViewY, frame.size.width, frame.size.height - collectionViewY - saveButtonHeight) collectionViewLayout:_flowLayout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.pagingEnabled = NO;//翻页
        _collectionView.backgroundColor = [UIColor clearColor];
        [self addSubview:_collectionView];
    }
    return self;
}

#pragma -mark 处理 “全选” 复选框
-(void)manageAllSelectedCheckBox{
    BOOL ischecked = YES;
    _checkDict = [PlistUtil getPLlistDicWitName:@"ConfigMenu.plist"];
    if (_checkDict != nil && _checkDict.count >0) {
        for (NSString *key in _checkDict) {
            NSString *sChecked = [_checkDict objectForKey:key];
            if ( ![key isEqualToString:@"menuMore"] && ![sChecked boolValue] ) {
                ischecked = NO;
                break;
            }
        }
    }else{
        for (StubObject *stub in _items) {
            NSString *sChecked = [stub getStringForKey:SELECTED_KEY withDefaultValue:@"0"];
            NSString *viewType = [stub getStringForKey:@"viewType" withDefaultValue:@""];
            if (![viewType isEqualToString:@"menuMore"] && ![sChecked boolValue]) {
                ischecked = NO;
                break;
            }
        }
    }
    [_allSelectCheckBox setChecked:ischecked];
    
}

-(void)action:(id)sender{
    //这个sender其实就是UIButton，因此通过sender.tag就可以拿到刚才的参数
    NSInteger i = [sender tag];
    switch (i) {
        case 0:
            //plist存储数据
            NSLog(@"点击保存按钮");
            [self saveData];
            break;
            
        default:
            break;
    }
}

-(void)saveData{
    NSMutableDictionary *plistDict;
    if (_checkDict != nil && [_checkDict count] > 0) {
        plistDict = [NSMutableDictionary dictionaryWithDictionary:_checkDict];
    }else{
        plistDict = [[NSMutableDictionary alloc ] init];
        for (StubObject *stub in _items) {
            [plistDict setObject:[stub getObjectForKey:SELECTED_KEY withDefaultValue:@"0"] forKey:[stub getID]];
        }
    }
    //写入文件
    [self saveData:plistDict toFile:@"ConfigMenu.plist"];
    [self showMBProgressHUDDialog];
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectCollectionMenuNotification" object:plistDict];
    [ViewControllerManager popViewControllerAnimated:YES];
}
-(void)saveData:(NSMutableDictionary *)data toFile:(NSString *)fileName{
    //获取路径
    NSString *path = [PlistUtil getPathWithName:fileName];
    //写入文件
    [data writeToFile:path atomically:YES];
}

- (void)showMBProgressHUDDialog{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self];
    [self addSubview:HUD];
    HUD.label.text = [JFLanguageManager stringWithKey:@"successfullySaved" table:Table_Tools comment:@"保存成功"];
    HUD.mode = MBProgressHUDModeText;
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    //    HUD.yOffset = 150.0f;
    //    HUD.xOffset = 100.0f;
    [HUD showAnimated:YES];
    [HUD hideAnimated:YES afterDelay:2];
//    [HUD showAnimated:YES whileExecutingBlock:^{
//        sleep(2);
//    } completionBlock:^{
//        [HUD removeFromSuperview];
//    }];
}

#pragma -mark 2 创建组件
-(void)creationComplete{
    if (_flowLayout) {
        //！！！ cell的横向间距
        _flowLayout.minimumInteritemSpacing = 0;
        NSInteger width = self.frame.size.width/_columnCount - 1;
        _flowLayout.itemSize=CGSizeMake(width ,width);
        [_flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        
    }
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[EFSelectCollectionMenuCell class] forCellWithReuseIdentifier:@"CollectionViewIdentifier"];
    
    
}

#pragma -mark section
-(NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    NSInteger sections = ceil(((double)_items.count)/_columnCount);
    return sections;
}

#pragma -mark items
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger totalSection = ceil(((double)_items.count)/_columnCount);
    if (section == totalSection - 1) {
        return _items.count - section * _columnCount;
    }else{
        return _columnCount;
    }
}

#pragma -mark - cell 菜单相关
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EFSelectCollectionMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewIdentifier" forIndexPath:indexPath];
    
    if(cell.imageWidth == 0 && cell.imageHeight == 0 && cell.titleHeight == 0){
        cell.imageWidth = _cellImageWidth;
        cell.imageHeight = _cellImageHeight;
        cell.titleHeight = _cellTitleHeight;
        cell.titleFontSize = _cellTitleFontSize;
        cell.titleColor = _cellTitleTextColor;
        cell.backgroundColor = _cellBackgroudColor;
        
        [cell creationComplete];
    }
    
    NSInteger index = [self getIndexByIndexPath:indexPath];
    StubObject *currentStubObject = [_items objectAtIndex:index];
    //    cell.image = [UIImage imageNamed:@"test_Image"];
    cell.imagePath = [currentStubObject getStringForKey:@"menuIcon" withDefaultValue:@"title"];
    cell.title = [currentStubObject getStringForKey:@"caption" withDefaultValue:@"title"];
    
    //判断checked：
    cell.isChecked = [self itemIsChecked:currentStubObject];
    
    //如果是“更多”，隐藏cell
    NSString *viewType = [currentStubObject getStringForKey:@"viewType" withDefaultValue:@""];
    if ([viewType isEqualToString:@"menuMore"]) {
        [cell setHidden:YES];
    }else{
        [cell setHidden:NO];
    }
    return cell;
}

#pragma -mark 判断checked
-(BOOL)itemIsChecked:(StubObject *)stubObject{
    //if plist 有值，从 plist 读取数据
    //else 从 stubObject 中读取数据
    BOOL isChecked;
    if(_checkDict != nil && _checkDict.count >0){
        NSString *isCheckedStr = [_checkDict objectForKey:[stubObject getID]];
        isChecked = [isCheckedStr boolValue];
    }else{
        isChecked = [[stubObject getStringForKey:SELECTED_KEY withDefaultValue:@"0"] boolValue];
    }
    return isChecked;
}

#pragma -mark 定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1, 1, 0, 0);
}

#pragma -mark 点击调用delegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger index = [self getIndexByIndexPath:indexPath];
    [self changeCheckBoxState:index];
    //调用delegate
    if (_selectCollectionMenuDelegate != nil && [_selectCollectionMenuDelegate respondsToSelector:@selector(selectCollectionMenu:didSelectItemAtIndex:)]) {
        [_selectCollectionMenuDelegate selectCollectionMenu:self didSelectItemAtIndex:index];
    }
}
#pragma -mark 改变checkbox选中状态
-(void)changeCheckBoxState:(NSInteger)index{
    StubObject *stub = [_items objectAtIndex:index];
    BOOL checked = [[stub getStringForKey:SELECTED_KEY withDefaultValue:@"0"] boolValue];
    if (checked) {
        [stub setString:@"0" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"0" forKey:[stub getID]];
        //处理全选复选框
        [_allSelectCheckBox setChecked:NO];
    }else{
        [stub setString:@"1" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"1" forKey:[stub getID]];
        //处理全选复选框
        BOOL allChecked = YES;
        for (StubObject *stub2 in _items) {
            BOOL checked2 = [self itemIsChecked:stub2];
            NSString *viewType = [stub2 getStringForKey:@"viewType" withDefaultValue:@""];
            if (!checked2 && ![viewType isEqualToString:@"menuMore"]) {
                allChecked = NO;
                break;
            }
        }
        _allSelectCheckBox.checked = allChecked;
    }
    [_collectionView reloadData];
}
#pragma -mark 根据indexPath，计算出index
-(NSInteger)getIndexByIndexPath:(NSIndexPath *)indexPath{
    NSInteger index = indexPath.section * _columnCount + indexPath.row;
    return index;
}
#pragma -mark selectAll
-(void)selectAll{
    for (StubObject *stub in _items) {
        [stub setString:@"1" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"1" forKey:[stub getID]];
        
    }
    [_collectionView reloadData];
}

#pragma -mark deselectAll
-(void)deselectAll{
    for (StubObject *stub in _items) {
        [stub setString:@"0" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"0" forKey:[stub getID]];
    }
    [_collectionView reloadData];
}


-(void)reloadData{
    [_collectionView reloadData];
}


@end
